//
//  QGAdhocUploadController.m
//  车福内测
//
//  Created by heew on 15/12/8.
//  Copyright © 2015年 heew. All rights reserved.
//

#import "QGAdhocUploadController.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"

@interface QGAdhocUploadController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *directory; /**<#属性名#> */
@property (strong, nonatomic) NSURL *parentPath; /**父路径 */
@property (strong, nonatomic) NSFileManager *fileMgr; /**文件管理器 */
@property (strong, nonatomic) void (^myProgressBlock)(NSProgress *progress); /**进度闭包  */
@property (strong, nonatomic) NSProgress *uploadProgress; /**上传进度 */
@end

@implementation QGAdhocUploadController
- (NSFileManager *)fileMgr {
    if (_fileMgr == nil) {
        _fileMgr = [NSFileManager defaultManager];
    }
    return _fileMgr;
}
- (NSMutableArray *)directory {
    if (_directory == nil) {
        _directory = [NSMutableArray array];
    }
    return _directory;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *path = @"/Users/heew";
    NSURL *url = [NSURL URLWithString:path];
    [self updateTableViewWithUrl:url];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"向上" style:UIBarButtonItemStylePlain target:self action:@selector(lastPage)];
    self.tabBarItem.title = @"上传";
    self.tabBarItem.image = [UIImage imageNamed:@"upload"];
}


- (void)lastPage {
    NSURL *lastUrl = self.parentPath.URLByDeletingLastPathComponent;
    [self updateTableViewWithUrl:lastUrl];
}
#pragma mark - tableView datasource
// 组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 每一组的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _directory.count;
}

// 每一个行的细节
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    NSURL *url = _directory[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        UIProgressView *progressView = [[UIProgressView alloc] init];
        progressView.tag = 100;
        progressView.hidden = YES;
        [cell.contentView addSubview:progressView];
        CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
        progressView.progressTintColor = [UIColor orangeColor];
        progressView.trackTintColor = [UIColor blueColor];
        progressView.frame = CGRectMake(16, 40, screenW - 20, 8);
    }
    NSString *string = [url.lastPathComponent stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [self.fileMgr attributesOfItemAtPath:url.path error:nil];
    UIProgressView *progressView = (UIProgressView *)[cell viewWithTag:100];
    progressView.hidden = NO;
    if ([dict[@"NSFileType"] isEqualToString:@"NSFileTypeDirectory"]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    if ([url.pathExtension isEqualToString:@"ipa"]) {
        progressView.observedProgress = self.uploadProgress;
        progressView.hidden = NO;
    }else {
        progressView.observedProgress = nil;
        progressView.hidden = YES;
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@",string];
    return cell;
}

#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSURL *url = _directory[indexPath.row];
    if ([url.pathExtension isEqualToString:@"ipa"]) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIProgressView *progressView = (UIProgressView *)[cell viewWithTag:100];
        progressView.hidden = NO;
        [self uploadFileWithUrl:url andProgress:^(NSProgress *progress) {
            progressView.observedProgress = progress;
        }];
    }else {
        [self updateTableViewWithUrl:url];
    }
}

- (void)updateTableViewWithUrl:(NSURL *)url {
    NSArray *array = [self.fileMgr contentsOfDirectoryAtURL:url includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
    [self.directory removeAllObjects];
    [self.directory addObjectsFromArray:array];
    [self.tableView reloadData];
    self.parentPath = url;
}

- (void)uploadFileWithUrl:(NSURL *)url andProgress:(void (^)(NSProgress *progress))progressBlock
{
    NSDictionary *param = @{@"uKey" : @"0a4bac562ae258ad921e24ef1ab72087",
                            @"_api_key" : @"0f100573a132929b1fc0abc9d3e72615"};
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://www.pgyer.com/apiv1/app/upload" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:url name:@"file" error:nil];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, NSDictionary *responseObject, NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:error.description];
        } else {
            NSDictionary *dict = responseObject[@"data"];
//            appBuildVersion = 2;
//            appCreated = "2015-12-09 07:35:07";
//            appDescription = "";
//            appFileSize = 6013655;
//            appIcon = 482984d0909ca626e38ba424f446dc61;
//            appIdentifier = "com.autozi.O2OGarage";
//            appIsLastest = 1;
//            appKey = 8242d5ffcf5a77acbf6e3d79d8554f67;
//            appName = "\U8f66\U798f\U7ba1\U5bb6\U5546\U5bb6\U7248";
//            appScreenshots = "";
//            appShortcutUrl = zZbL;
//            appType = 1;
//            appUpdateDescription = "";
//            appUpdated = "2015-12-09 07:35:07";
//            appVersion = "1.2.0";
//            appVersionNo = "1.2.0";
//            userKey = 0a4bac562ae258ad921e24ef1ab72087;
            NSString *status = [NSString stringWithFormat:@"上传成功\n%@\n%@\n",dict[@"appName"],dict[@"appCreated"]];
            [SVProgressHUD showInfoWithStatus:status];
        }
    }];
    
//    self.progressView.observedProgress = progress;
    progressBlock ? progressBlock(progress) : nil;
    self.uploadProgress = progress;
    [uploadTask resume];
}


@end
